Different Ways to Add Parentheses || Merge k Sorted Lists

Different Ways to Add Parentheses

Question

Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and *.

Example 1

Input: "2-1-1".

1
2
((2-1)-1) = 0
(2-(1-1)) = 2

Output: [0, 2]

Example 2

Input: "2*3-4*5"

1
2
3
4
5
(2*(3-(4*5))) = -34
((2*3)-(4*5)) = -14
((2*(3-4))*5) = -10
(2*((3-4)*5)) = -10
(((2*3)-4)*5) = 10

Output: [-34, -14, -10, -10, 10]

Analysis

LeetCode Discuss - A recursive Java solution

从字符串头开始遍历,遇到符号将字符串划分为左右两部分part1和part2,对他们递归调用该函数,得到左右部分的结果集合list,利用双重循环对结果进行组合计算。

注意:

在最终得到res的大小为0的时候,代表该字符串不存在符号,直接返回input字符串的数值即可。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class Solution {
public List<Integer> diffWaysToCompute(String input) {
List<Integer> res=new ArrayList<>();
for(int i=0;i<input.length();i++){
char c=input.charAt(i);
if(c=='-'||c=='*'||c=='+'){
String part1=input.substring(0,i);
String part2=input.substring(i+1);
List<Integer> pret1=diffWaysToCompute(part1);
List<Integer> pret2=diffWaysToCompute(part2);
for(Integer num1:pret1){
for(Integer num2:pret2){
int tmp=0;
switch(c){
case '-':
tmp=num1-num2;
break;
case '+':
tmp=num1+num2;
break;
case '*':
tmp=num1*num2;
break;
}
res.add(tmp);
}
}
}
}
if(res.size()==0){
res.add(Integer.valueOf(input));
}
return res;
}
}

Merge k Sorted Lists

Question

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Analysis

中文C++ 思路

A Java Solution based on Priority Queue

  • 重新定义PriorityQueue的comparator方法,Priority Queue 使用方法如下:

    • 插入方法(offer()、poll()、remove() 、add() 方法)时间复杂度为O(log(n))
    • remove(Object) 和 contains(Object) 时间复杂度为O(n)
    • 检索方法(peek、element 和 size)时间复杂度为常量。

    Priority Queue使用方法

    Priority Queue时间复杂度分析及示例

  • 将所有节点添加到队列后,循环出队加入结果链表,当加入节点next不为空的时候,将该next节点再次加入队列中

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists.length==0)
return null;
if(lists.length==1)
return lists[0];
PriorityQueue<ListNode> queue=new PriorityQueue<ListNode>(new Comparator<ListNode>(){
@Override
public int compare(ListNode o1, ListNode o2){
if(o1.val<o2.val)
return -1;
else if(o1.val==o2.val)
return 0;
else
return 1;
}
});
ListNode res=new ListNode(0);
ListNode pointer=res;
for(ListNode tmp:lists){
if(tmp!=null){
queue.offer(tmp);
}
}
while(!queue.isEmpty()){
pointer.next=queue.poll();
pointer=pointer.next;
if(pointer.next!=null)
queue.offer(pointer.next);
}
return res.next;
}
}